package com.exam.scjp5.objectives.section_3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ExampleSerializable1
{
    public static void main(String args[])
    {
        
        try
        {
            FileOutputStream fout = new FileOutputStream(new File("serializable1.dat"));
            ObjectOutputStream ob = new ObjectOutputStream(fout);
            SerializableChild c = new SerializableChild();
            ob.writeObject(c);
            ob.flush();
            ob.close();
            fout.close();
            System.out.println("Done serialized!!!\n Now deserialized.");
            
            FileInputStream fin = new FileInputStream(new File("serializable1.dat"));
            ObjectInputStream obin = new ObjectInputStream(fin);
            c = (SerializableChild)obin.readObject();            
            obin.close();
            fin.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class NotSerializableGrandParent
{
    int i = 10;
    
    // If you remove this default constructor, program will throw InvalidClassException
    // when it tries to deserialize the object.
    public NotSerializableGrandParent(){System.out.println("NotSerializableGrandParent : " + i);}

    public NotSerializableGrandParent(int i)
    {
        this.i = i;
        System.out.println("NotSerializableGrandParent : " + i);
    }
}

class NotSerializableParent extends NotSerializableGrandParent
{
    int i = 10;
    
    // If you remove this default constructor, program will throw InvalidClassException
    // when it tries to deserialize the object.
    public NotSerializableParent(){System.out.println("NotSerializableParent : " + i);}

    public NotSerializableParent(int i)
    {
        super(i);
        this.i = i;
        System.out.println("NotSerializableParent : " + i);
    }
}

class SerializableChild extends NotSerializableParent implements Serializable
{
    int i = 0;
    {
        System.out.println("Initializer.");
    }
    // The following will shows you NotSerializableException when you try to run.
    // That is because NotSerializableGrandParent does not implement Serializable interface.
    //-- NotSerializableGrandParent gp = new NotSerializableGrandParent();
    
    public SerializableChild()
    {
        super(20);
        System.out.println("SerializableChild : " + i);
    }
}